﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
using AF.Library;
using System.Configuration;
using Bussiness.Config;
using Bussiness.Entity;
using Bussiness.Manager;
namespace DSC
{
    public partial class frmChooseDB : AfChildrenForm
    {
        public frmChooseDB()
        {
            InitializeComponent();
            lstDB.Text = ConfigurationManager.AppSettings["SERVER"];
            lstDatabase.Text = ConfigurationManager.AppSettings["DATABASE"];
            txtUsername.Text = Encrypt.FDecrypt(ConfigurationManager.AppSettings["UserName"]);
            txtPassword.Text = Encrypt.FDecrypt(ConfigurationManager.AppSettings["Password"]);
            try
            {
                string connectionString = @"server=" + ConfigurationManager.AppSettings["SERVER"] + ";database=" + ConfigurationManager.AppSettings["DATABASE"] + ";uid=" + ConfigurationManager.AppSettings["UserName"] + ";pwd=" + ConfigurationManager.AppSettings["Password"];
                System.Data.SqlClient.SqlConnection SqlCon = new System.Data.SqlClient.SqlConnection(connectionString);
                SqlCon.Open();

                // DMSDB
                DataTable tb = PT_ConfigManager.CreateInstant().SelectAll();
                DataRow[] rows = tb.Select("ConfigCode='DMSDB'");
                txtDMSDB.Text = rows[0]["ConfigValue"].ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Không thể kết nối tới cơ sở dữ liệu. Vui lòng chọn cơ sở dữ liệu mới.");
            }
        }
        private void lstDB_SelectedIndexChanged(object sender, EventArgs e)
        {
            lstDatabase.Items.Clear();
            try
            {
                if (!string.IsNullOrEmpty(lstDB.Text.Trim()))
                {
                    try
                    {
                        System.Data.SqlClient.SqlConnection SqlCon = new System.Data.SqlClient.SqlConnection("server=" + lstDB.Text.Trim() + ";uid=" + txtUsername.Text.Trim() + ";pwd=" + txtPassword.Text.Trim());
                        SqlCon.Open();

                        System.Data.SqlClient.SqlCommand SqlCom = new System.Data.SqlClient.SqlCommand();
                        SqlCom.Connection = SqlCon;
                        SqlCom.CommandType = CommandType.StoredProcedure;
                        SqlCom.CommandText = "sp_databases";

                        System.Data.SqlClient.SqlDataReader SqlDR;
                        SqlDR = SqlCom.ExecuteReader();

                        while (SqlDR.Read())
                        {
                            lstDatabase.Items.Add(SqlDR.GetString(0));
                        }
                    }
                    catch (Exception x)
                    {
                        MessageBox.Show("Không thể kết nối đến server. Vui lòng kiểm tra thông tin đăng nhập hoặc chọn lại server khác.");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void lstDB_Click(object sender, EventArgs e)
        {
            if (lstDB.Items.Count <= 0)
            {
                lstDB.Items.Clear();
                SqlDataSourceEnumerator sdse = SqlDataSourceEnumerator.Instance;
                DataTable table = sdse.GetDataSources();
                foreach (DataRow row in table.Rows)
                {
                    lstDB.Items.Add(row["ServerName"].ToString() + (!string.IsNullOrEmpty(row["InstanceName"].ToString()) ? "\\" + row["InstanceName"].ToString() : ""));
                }
            }   
        }

        private void btLoadDB_Click(object sender, EventArgs e)
        {
            lstDB.Items.Clear();
            SqlDataSourceEnumerator sdse = SqlDataSourceEnumerator.Instance;
            DataTable table = sdse.GetDataSources();
            foreach (DataRow row in table.Rows)
            {
                lstDB.Items.Add(row["ServerName"].ToString() + (!string.IsNullOrEmpty(row["InstanceName"].ToString()) ? "\\" + row["InstanceName"].ToString() : ""));
            }
        }

        private void lstDatabase_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstDatabase.Items.Count <= 0)
                {
                    if (!string.IsNullOrEmpty(lstDB.Text.Trim()))
                    {
                        lstDatabase.Items.Clear();
                        try
                        {
                            System.Data.SqlClient.SqlConnection SqlCon = new System.Data.SqlClient.SqlConnection("server=" + lstDB.Text.Trim() + ";uid=" + txtUsername.Text.Trim() + ";pwd=" + txtPassword.Text.Trim());
                            SqlCon.Open();

                            System.Data.SqlClient.SqlCommand SqlCom = new System.Data.SqlClient.SqlCommand();
                            SqlCom.Connection = SqlCon;
                            SqlCom.CommandType = CommandType.StoredProcedure;
                            SqlCom.CommandText = "sp_databases";

                            System.Data.SqlClient.SqlDataReader SqlDR;
                            SqlDR = SqlCom.ExecuteReader();

                            while (SqlDR.Read())
                            {
                                lstDatabase.Items.Add(SqlDR.GetString(0));
                            }
                        }
                        catch (Exception x)
                        {
                            MessageBox.Show("Không thể kết nối đến server. Vui lòng kiểm tra thông tin đăng nhập hoặc chọn lại server khác.");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btSaveDBInfo_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(lstDB.Text.Trim()))
                {
                    MessageBox.Show("Chọn Server Name");
                }
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.AppSettings.Settings["SERVER"].Value = lstDB.Text.Trim();
                config.AppSettings.Settings["DATABASE"].Value = lstDatabase.Text.Trim();
                config.AppSettings.Settings["UserName"].Value = Encrypt.FEncrypt(txtUsername.Text.Trim());
                config.AppSettings.Settings["Password"].Value = Encrypt.FEncrypt(txtPassword.Text.Trim());
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
                this.Close();
                ConnectionConfig.ConnectionString = @"server=" + ConfigurationManager.AppSettings["SERVER"] + ";database=" + ConfigurationManager.AppSettings["DATABASE"] + ";uid=" + Encrypt.FDecrypt(ConfigurationManager.AppSettings["UserName"]) + ";pwd=" + Encrypt.FDecrypt(ConfigurationManager.AppSettings["Password"]);
                PT_ConfigEntity ConObj = PT_ConfigManager.CreateInstant().SelectByConfigCodeLST("DMSDB")[0];
                if (ConObj != null)
                {
                    ConObj.ConfigValue = txtDMSDB.Text.Trim();
                    PT_ConfigManager.CreateInstant().Update(ConObj);
                }
                MessageBox.Show("Chọn cơ sở dữ liệu thành công.");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Thao tác không thành công. Vui lòng thử lại.");
            }
        }

        private void btReLoadDatabase_Click(object sender, EventArgs e)
        {
            lstDatabase.Items.Clear();
            try
            {
                if (!string.IsNullOrEmpty(lstDB.Text.Trim()))
                {
                    try
                    {
                        System.Data.SqlClient.SqlConnection SqlCon = new System.Data.SqlClient.SqlConnection("server=" + lstDB.Text.Trim() + ";uid=" + txtUsername.Text.Trim() + ";pwd=" + txtPassword.Text.Trim());
                        SqlCon.Open();

                        System.Data.SqlClient.SqlCommand SqlCom = new System.Data.SqlClient.SqlCommand();
                        SqlCom.Connection = SqlCon;
                        SqlCom.CommandType = CommandType.StoredProcedure;
                        SqlCom.CommandText = "sp_databases";

                        System.Data.SqlClient.SqlDataReader SqlDR;
                        SqlDR = SqlCom.ExecuteReader();

                        while (SqlDR.Read())
                        {
                            lstDatabase.Items.Add(SqlDR.GetString(0));
                        }
                    }
                    catch (Exception x)
                    {
                        MessageBox.Show("Không thể kết nối đến server. Vui lòng kiểm tra thông tin đăng nhập hoặc chọn lại server khác.");
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        
    }
}
